#include <Windows.h>

#include <sstream>

#include "FileVersion.h"
#pragma comment (lib, "Version.lib")

using namespace std;

CFileVersion::CFileVersion(void)
{
}


CFileVersion::~CFileVersion(void)
{
}

CFileVersion* CFileVersion::GetVersionPtr(const wstring& file) throw(...)
{
	CFileVersion* fv = new CFileVersion();

	int size = GetFileVersionInfoSizeW(file.c_str(), NULL);
	char* data = new char[size];
	if(!GetFileVersionInfoW(file.c_str(), NULL, size, data))
	{
		delete[] data;
		throw wstring(L"Cannot query file version, file ->") + file;
	}
	else
	{
		VS_FIXEDFILEINFO* pVersion;
		UINT nLength;
		VerQueryValueW(data, L"\\", (LPVOID*)&pVersion, &nLength); 
		
		fv->Major		= HIWORD(pVersion->dwFileVersionMS);
		fv->Minor		= LOWORD(pVersion->dwFileVersionMS);
		fv->Build		= HIWORD(pVersion->dwFileVersionLS);
		fv->Revision	= LOWORD(pVersion->dwFileVersionLS);

		delete[] data;
	}

	return fv;
}

unique_ptr<CFileVersion> CFileVersion::GetVersion(const wstring& file) throw(...)
{
	unique_ptr<CFileVersion> upfv(GetVersionPtr(file));
	return upfv;
}

wstring CFileVersion::ToString() const throw()
{
	wostringstream os;
	os << Major << L'.' << Minor << L'.' << Build << L'.' << Revision;
	return os.str();
}

string CFileVersion::ToStringA() const throw()
{
	ostringstream os;
	os << Major << '.' << Minor << '.' << Build << '.' << Revision;
	return os.str();
}

